window.addEventListener(
  'message',
  function (event) {
    // We only accept messages from ourselves
    // if (event.source != window) return
    if (event.data.type && event.data.type == 'FROM_PAGE') {
      console.log('Content script received: ' + event.data.text)
      chrome.runtime.sendMessage(event.data.text)
    }
  },
  false
)

// 监听长连接
chrome.runtime.onConnect.addListener(function (port) {
  if (port.name == 'test-connect') {
    port.onMessage.addListener(function (msg) {
      console.log('收到长连接消息：', msg)
      if (msg.question == '你是谁啊？') port.postMessage({ answer: '我是你爸！' })
    })
  }
})

let myRequest = new Request('http://httpbin.org/post')

// 聊boss
let time = 0 // 打招呼个数
let timer // 计时器
function scrollList(delay = 10) {
  return new Promise((resolve, reject) => {
    clearInterval(timer)
    timer = setInterval(() => {
      if (time > 200) {
        clearInterval(timer)
        resolve()
      }
      document.documentElement.scrollTop += 80
    }, delay)
  })
}

function filterDom() {
  console.log('jquery',jQuery, $)
  return $('#recommend-list .card-inner').find('.iboss-icon_man').parents('li').find('.info-labels')
  // todo: don't need jquery
  // const y = Array.from(myMultipleElements, (x) => Array.from(x.querySelectorAll('.foo'))).flat()
  // const parents = Array.from(document.querySelectorAll('#recommend-list .card-inner .iboss-icon_man'), x => x.closest('li'))
  // const myMultipleElements = document.querySelectorAll('#recommend-list .card-inner .iboss-icon_man')
  // return Array.from(document.querySelectorAll('.menus-wrapper li'), x => Array.from(x.querySelectorAll('span'))).flat();
}

function filterGreet() {
  filterDom().each(function (index, item) {
    var age = parseInt($(item).find('.label-text').eq(0).text().replace('岁', ''))
    if (age <= 29 && age >= 20 && time <= 200) {
      time += 1
      console.log('符合年龄: ' + age + '岁，第几个:' + time + '打招呼间隔时间:' + time + 's')
      window.postMessage({
        ageRanges: [20, 29],
        age: age,
        interval: time,
      })
      if (time < 200) {
        scrollList().then(() => {
          clickGreet()
        })
      }
    }
  })
}

function clickGreet(interval) {
  filterDom().each((index, item) => {
    interval = 500 * index
    setTimeout(function () {
      $(item).parents('li').find('.btn-greet').trigger('click')
    }, interval)
  })
}
